package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //pre, rooting, post, error 过滤器
    @Override
    public String filterType() {
//        return "pre";
        return FilterConstants.PRE_TYPE;
    }
    //指定过滤器的顺序号
    @Override
    public int filterOrder() {
        //有5个默认的多滤器,自己的过滤器加到末尾
        return 6;
    }
    //针对当前请求,判断是否执行过滤代码
    //如果调用 item-service,检查是否登录,否则就不检查登录,直接访问,
    @Override
    public boolean shouldFilter() {
        //先获取当前请求的上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //当前请求的服务id
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);//serviceId
        //调用的是否是 item-service
        return "item-service".equals(serviceId);
    }
    //这是过滤代码
    @Override
    public Object run() throws ZuulException {
        //获得上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //获得 request 对象
        HttpServletRequest request = ctx.getRequest();
        //http://localhost:3001/item-service/sdafsadf?token=qrqeqw423err
        //接收token
        String token = request.getParameter("token");
        //如果没有token,阻止继续调用,直接返回响应
        //判断是否存在token
        if (StringUtils.isBlank(token)){
            //阻止继续调用
            ctx.setSendZuulResponse(false);
            //直接返回响应
            //JsonResult --- {code:1,msg:xxx,data:null}
            ctx.addZuulResponseHeader("Content-Type","application/json;chatset=UTF-8");//协议头
            ctx.setResponseBody(JsonResult.err().code(400).msg("未登录!!!").toString());//协议体
        }
        return null;// 当前zull 版本中,这个返回值没有使用
    }
}
